package com.zxc.service.impl;

import com.zxc.Util.windWeather;
import com.zxc.dao.UserDao;
import com.zxc.model.*;
import com.zxc.model.Crops.CropsVO;
import com.zxc.model.Diseases.DiseasesHistory;
import com.zxc.model.ParkDaily.HealerRecord;
import com.zxc.model.ParkDaily.ParkState;
import com.zxc.service.UserService;
import com.zxc.model.ParkDetails;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    public int checkAccount(String account,String password)
    {
        User user = new User();
        user.setAccount(account);
    if(userDao.selectUserById(user)!=null){
        if(password.equals(userDao.selectUserById(user).getPassword())){
            return 1;
        }
    }
        return 0;
    }

    public User getUser(String userName){
        User user = new User();
        user.setAccount(userName);
        User UserDao =userDao.selectUserById(user);
         return UserDao;
    }


    public List<User>getUserList(User user){
        return userDao.selectUserToPark(user);
    }
    public List<ParkDetails> getParkByUserId(String id){
//        调用dao成方法 其实就是去执行对应的sql语句
        List<ParkDetails> list= userDao.selectParkByUserId(id);
        return list;
    }

    public List<ParkDetails> getParkByUser(ParkDetails parkDetails){
        List<ParkDetails> list= userDao.selectParkByUser(parkDetails);
        return list;
    }
//    获取园区数据
    public ParkState getParkOne(ParkState parkState){
        ParkState vo=userDao.selectPark(parkState);
//        做价格处理 2020-3-5 待处理
//        327 引入天气和病症因素
        vo.setMM(vo.getYield()*vo.getMu());
        return vo;
    }

    public List<seeds> getSeedList(seeds seeds){
        List<com.zxc.model.seeds> list= userDao.selectSeedsWarehouseBySeeds(seeds);
        return list;
    }



    //  获取对应账号的农具仓库 数据
    public List<Tools> getToolsList(Tools tools){
        List<Tools> list= userDao.selectToolsByTools(tools);
        return list;
    }
    //  获取对应账号的肥料仓库 数据
    public List<Fertilizer> getFertilizerList(Fertilizer fertilizer){
            List<Fertilizer> list= userDao.selectFertilizerByFertilizer(fertilizer);
//        PageInfo<Fertilizer> page = new PageInfo<Fertilizer>(list);
        return list;
    }
    // 获取农药信息
    public List<Pesticide> getPesticideList(Pesticide pesticide){
        List<Pesticide> list= userDao.selectPesticideByPesticide(pesticide);
        return list;
    }

    //管理员插入仓库数据


    @Override
    public int setPesticide(Pesticide pesticide) {
        pesticide.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        int i=userDao.insertPesticide(pesticide);
        return i;
    }

    @Override
    public int setPesticideWarehouse(Pesticide pesticide) {
        pesticide.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        int i=userDao.insertPesticideWarehouse(pesticide);
        return i;
    }
    @Override
    public int setFertilizerWarehouse(Fertilizer fertilizer) {
        fertilizer.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        int i=userDao.insertFertilizerWarehouse(fertilizer);
        return i;
    }
    @Override
    public int setSeedsWarehouse(seeds seeds) {
        seeds.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        int i=userDao.insertSeedsWarehouse(seeds);
        return i;
    }
    @Override
    public int setToolsWarehouse(Tools tools) {
        tools.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        int i=userDao.insertToolsWarehouse(tools);
        return i;
    }
    //用户插入仓库数据
    @Override
    public int setUserPesticideWarehouse(Pesticide pesticide) {
        pesticide.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        int i=userDao.insertUserPesticideWarehouse(pesticide);
        return i;
    }
    @Override
    public int setUserFertilizerWarehouse(Fertilizer fertilizer) {
        fertilizer.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        int i=userDao.insertUserFertilizerWarehouse(fertilizer);
        return i;
    }
    @Override
    public int setUserSeedsWarehouse(seeds seeds) {
        seeds.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        int i=userDao.insertUserSeedsWarehouse(seeds);
        return i;
    }
    @Override
    public int setUserToolsWarehouse(Tools tools) {
        tools.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        int i=userDao.insertUserToolsWarehouse(tools);
        return i;
    }
    //用户查询各个仓库的数据
    @Override
    public List<Tools> getUserToolsList(Tools tools){
        //通过userId查询员工工具仓库数据
        List<Tools> list= userDao.selectUserToolsWarehouseByUserId(tools);
        return list;
    }
    @Override
    public List<seeds> getUserSeedsList(seeds seeds){
        //通过userId查询员工种子仓库数据
        List<com.zxc.model.seeds> list= userDao.selectUserSeedsWarehouseByUserId(seeds);
        return list;
    }
    @Override
    public List<Pesticide> getUserPesticideList(Pesticide pesticide){
        //通过userId查询员工农药仓库数据
        List<Pesticide> list= userDao.selectUserPesticideWarehouseByUserId(pesticide);
        return list;
    }
    @Override
    public List<Fertilizer> getUserFertilizerList(Fertilizer fertilizer){
        //通过userId查询员工农药仓库数据
        List<Fertilizer> list= userDao.selectUserFertilizerWarehouseByUserId(fertilizer);
        return list;
    }

    //记录园区日常信息及治疗物使用信息
    @Override
    public int recordParkDailyInfo(ParkState parkState) {
        //遍历参数对象内集合里面的各个对象
        HealerRecord healerRecord = new HealerRecord();
        List<Pesticide> pesticideslist=new ArrayList<>();
        List<Fertilizer> fertilizerlist=new ArrayList<>();
        for (int a = 0;a < parkState.getHealerRecordList().size();a++){
//
        healerRecord=parkState.getHealerRecordList().get(a);
//                        判断类型 是农药还是肥料
            if("1".equals(healerRecord.getType())){
                Pesticide pesticide = new Pesticide();
                pesticide.setPesticideId(parkState.getHealerRecordList().get(a).getTypeId());
                pesticide.setUserId(parkState.getUserId());
//判断是否有这个植物在仓库中，并且其数量会大于日程操作的量
                List<Pesticide> pesticide1 = userDao.selectUserPesticideWarehouseByUserId(pesticide);
                if(pesticide1.size()==0||pesticide1.get(0).getPesticideNum()<healerRecord.getHealerNum()){
                    return -200;
                }else {
                    Pesticide pesticide2=pesticide1.get(0);
                    float pa1=pesticide2.getPesticideNum();
                    float pa2=healerRecord.getHealerNum();
                    pesticide2.setPesticideNum(pa1-pa2);
                    pesticideslist.add(pesticide2);
                }
//                判断不是农药则是肥料
            }else {
                Fertilizer fertilizer = new Fertilizer();
                fertilizer.setFertilizerId(parkState.getHealerRecordList().get(a).getTypeId());
                fertilizer.setUserId(parkState.getUserId());
                List<Fertilizer> fertilizer1=userDao.selectUserFertilizerWarehouseByUserId(fertilizer);
                if(fertilizer1.size()==0||fertilizer1.get(0).getFertilizerNum()<healerRecord.getHealerNum()){
                    return -300;
                }else{
                    Fertilizer fertilizer2 =fertilizer1.get(0);
                    fertilizer2.setFertilizerNum(fertilizer2.getFertilizerNum()-healerRecord.getHealerNum());
                    fertilizerlist.add(fertilizer2);
                }
            }
        }
        if (pesticideslist.size()>0) {
            if (userDao.upDateUserPesticideWarehouseList(pesticideslist) < 1) {
                return -200;
            }
        }
        if (fertilizerlist.size()>0){
            if(userDao.upDateUserFertilizerWarehouseList(fertilizerlist)<1){
                return -200;
            }
        }
            parkState.setPsId(UUID.randomUUID().toString().replaceAll("-", ""));
            String hrParkId=parkState.getPsId();
            Date d = new Date();
            SimpleDateFormat dqsj = new SimpleDateFormat("yyyy-MM-dd");
            parkState.setStateTime(dqsj.format(d));
            int i=userDao.insertParkState(parkState);  //返回园区状态表数据库影响行数
            for (int a = 0;a < parkState.getHealerRecordList().size();a++){
                HealerRecord hr = new HealerRecord();
                //从HealerRecordList中获取对象
                hr = parkState.getHealerRecordList().get(a);
                //为对象设置主键以及记录时间
                hr.setHrId(UUID.randomUUID().toString().replaceAll("-", ""));
                hr.setHrParkid(hrParkId);
                hr.setRecordTime(dqsj.format(d));
                userDao.insertHealerRecord(hr);
            }
            return  i;
        }
    //查询园区历史
    @Override
    public List<ParkState> getParkStateHistory(ParkState parkState){
        return userDao.selectParkStateHistory(parkState);
    }
    @Override
    public int setParkToUserOk(List<ParkDetails> parkDetails){
        int k=-1;
        for (int i = 0; i < parkDetails.size(); i++) {
            ParkDetails parkDetails1 =new ParkDetails();
            parkDetails1.setId(parkDetails.get(i).getId());
            parkDetails1.setUserId(parkDetails.get(i).getUserId());
            parkDetails1.setParkState(1);
            k+=userDao.updatePark(parkDetails1);
        }
        return k;
    }
    @Override
    public int setParkToUserNO(List<ParkDetails> parkDetails){
        int k=-1;
        for (int i = 0; i < parkDetails.size(); i++) {
            ParkDetails parkDetails1 =new ParkDetails();
            parkDetails1.setId(parkDetails.get(i).getId());
            parkDetails1.setUserId("kxzt");
            parkDetails1.setParkState(3);
            k+=userDao.updatePark(parkDetails1);
        }
        return k;
    }
    //人员数据操作
    @Override
    public int setUser(User user) {
        user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        String hashAlgorithnName="MD5";
        Object credentials = user.getPassword();
        Object salt = ByteSource.Util.bytes( user.getAccount());
        int hashIterations = 1;
        Object result = new SimpleHash(hashAlgorithnName,credentials,salt,hashIterations);
        user.setPassword(result.toString());
        user.setUserState(1);
        user.setImageUrl("/?????????????");
        int i=userDao.insertUserDate(user);
        return i;
    }

    //员工工作计划表插入
    @Override
    public int setPlan(Plan plan) {
        plan.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        Date d = new Date();
        SimpleDateFormat dqsj = new SimpleDateFormat("yyyy-MM-dd");
        plan.setInsertTime(dqsj.format(d));
        int i=userDao.insertUserPlan(plan);
        return i;
    }
//    删除计划
    public int deleteUserPlan(Plan plan) {
        int i=userDao.deleteUserPlan(plan);
        return i;
    }


    //插入病症历史信息表
    @Override
    public int setDiseasesHistory(DiseasesHistory diseasesHistory) {
        diseasesHistory.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        Date d = new Date();
        SimpleDateFormat dhDate = new SimpleDateFormat("yyyy-MM-dd");
        diseasesHistory.setVerifyTime(dhDate.format(d));
        int i=userDao.insertDiseasesHistory(diseasesHistory);
        return i;
    }

    public  List<Fertilizer> getFertilizer(){
        return userDao.selectFertilizer();
    }
    public List<Pesticide> getPesticide(){
        return userDao.selectPesticide();
    }
    public List<seeds> getSeed(@RequestBody seeds vo){
        User user = new User();
        user.setAccount(vo.getPageList().get(0).getAccount());
        vo.setUserId(user.getId());
        return userDao.selectSeed(vo);
    }


    public int ParkPlant(CropsVO vo){
        seeds s =new seeds();
        s.setUserId(vo.getUserId());
        s.setPlantId(vo.getPlantId());
        Float i=userDao.selectUserSeedsWarehouseByUserId(s).get(0).getSeedNum();
        if(i>=vo.getLeviteNum2()){
            s.setSeedNum(i-vo.getLeviteNum2());
            int g=-1;
            g=userDao.updateUserSeedsWarehouse(s);
            ParkDetails parkDetails =new ParkDetails();
            parkDetails.setId(vo.getParkId());
            parkDetails.setParkState(2);
            parkDetails.setPlantId(vo.getPlantId());
            g+=userDao.updatePark(parkDetails);
            return g;
        }else {
            return -1;
        }
    }

    public int updatePark(ParkDetails parkDetails){
        return userDao.updatePark(parkDetails);
    }

   public List<Plan> getPlantList(Plan plan){
//        明日计划
       int k=0;
       double tmpMax=0;
       double condCode=0;
       double pcpn=0;
       double windSpd=0;
       Date date = null;
       Date   date2 = null;
       windWeather vo =new windWeather();
       JSONObject object = new JSONObject(vo.getWeatherApi());
       JSONObject object1 = object.getJSONArray("HeWeather6").getJSONObject(0);
       int length =object1.getJSONArray("daily_forecast").length();
       List<Plan> list= userDao.selectPlan(plan);
       for (int i = 0; i <length; i++) {
           JSONObject s = object1.getJSONArray("daily_forecast").getJSONObject(i);
           SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
           try {
               date=formatter.parse(s.get("date").toString());
           } catch (ParseException e) {
               e.printStackTrace();
           }
//            获取当天天气的情况
           tmpMax=Double.parseDouble(s.get("tmp_max").toString());
           condCode=Double.parseDouble(s.get("cond_code_d").toString());
           pcpn=Double.parseDouble(s.get("pcpn").toString());
           windSpd=Double.parseDouble(s.get("wind_spd").toString());
//
           for (int j = k; j <list.size(); j++) {
               try {
                   date2=formatter.parse(list.get(j).getPlanTime());
               } catch (ParseException e) {
                   e.printStackTrace();
               }
               if(date.compareTo(date2)>0){
                   break;
               }else {
                   list.get(j).setCondCode(vo.getCondCode(condCode));
                   list.get(j).setTemperature(vo.getTmpMax(tmpMax));
                   list.get(j).setWindSc(vo.getWindSc(windSpd));
                   list.get(j).setPcpn(vo.getPcpn(pcpn));
                   k++;
               }
           }
       }
        return list;
   }

    public List<Plan> getAllPlantList(Plan plan){
        return userDao.selectAllPlan(plan);
    }











}
